<template>
  <div class="form-control w-full" :class="{'dark-mode': isDarkMode}">
    <label v-if="label" class="label">
      <span class="label-text">{{ label }}</span>
    </label>
    <div class="flex flex-wrap gap-4">
      <label
        v-for="option in options"
        :key="option.value"
        class="label cursor-pointer justify-start gap-2"
      >
        <input
          type="checkbox"
          class="checkbox"
          :class="{
            'checkbox-error': error,
            'checkbox-disabled': disabled
          }"
          :checked="isChecked(option.value)"
          @change="handleChange(option.value)"
          :disabled="disabled"
        />
        <span class="label-text">{{ option.label }}</span>
      </label>
    </div>
    <label v-if="error" class="label">
      <span class="label-text-alt text-error">{{ error }}</span>
    </label>
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from "vue";

interface Option {
  label: string;
  value: string | number;
}

interface Props {
  modelValue: (string | number)[];
  options: Option[];
  label?: string;
  error?: string;
  disabled?: boolean;
  isDarkMode?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
  disabled: false,
  options: () => [],
  isDarkMode: true
});

const emit = defineEmits<{
  (e: 'update:modelValue', value: (string | number)[]): void;
}>();

const isChecked = (value: string | number) => {
  return props.modelValue.includes(value);
};
const checkbox = ref<string | number | null>('');
const handleChange = (value: string | number) => {
  const newValue = [...props.modelValue];
  const index = newValue.indexOf(value);

  checkbox.value = value;
  if (index === -1) {
    newValue.push(value);
  } else {
    newValue.splice(index, 1);
  }
  emit('update:modelValue', newValue);
};

defineExpose({
  checkbox
});
const isDarkMode = ref(true);
watch(() => props.isDarkMode, (newValue) => {
  isDarkMode.value = newValue;
}, { immediate: true, deep: true });
</script>
<style scoped>

/* 深色模式适配 */
.dark-mode {
  background: transparent !important;
}
.dark-mode .checkbox {
  background-color: #ffffff !important;
  border-color: #d1d5db !important;
}

.dark-mode .checkbox:checked {
  background-color: #1e40af !important;
  border-color: #1e40af !important;
}

.dark-mode .checkbox:disabled {
  background-color: #f3f4f6 !important;
  border-color: #d1d5db !important;
  cursor: not-allowed !important;
}

.dark-mode .label-text {
  color: var(--color-text-primary) !important;
}

@media (max-width: 1024px) {
  .checkbox {
    width: 14px !important;
    height: 14px !important;
  }

  .label-text {
    font-size: 12px !important;
  }

  .dark-mode .label-text {
    color: var(--text-color);
  }

  .gap-2 {
    gap: 0.5rem !important;
  }

  .gap-4 {
    gap: 0.75rem !important;
  }

  .label {
    padding: 0.25rem 0 !important;
  }
}
</style>
